package com.twp.auth.repository.auth;

import com.twp.auth.domain.authority.Menu;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.Collection;
import java.util.List;

@Repository
public interface MenuRepository extends JpaRepository<Menu, Integer>, JpaSpecificationExecutor<Menu> {

    List<Menu> findByCodeIn(Collection<String> codes);

    Menu findAllByCode(String code);

    @Query(
            nativeQuery = true,
            value = "SELECT * FROM twp_menu WHERE parent_id IS ?1"
    )
    Menu findAllByParentId(String parentId);

    List<Menu> findByIdInOrderByMenuOrderAscIdAsc(Collection<String> codes);

    @Query(value = "select distinct m.id from twp_role_user tu ,twp_role_menu tm ,twp_menu m where  tm.roleId = tu.roleId  and m.id = tm.menuId and tu.manageUserId = :urid", nativeQuery = true)
    List<String> findMenuIdByUid(@Param("urid") Integer urid);

    //List<Menu> findByMpid(String mpId);
    @Query(
            nativeQuery = true,
            value = "SELECT menu.* FROM twp_menu menu " +
                    "INNER JOIN twp_role_menu role_menu ON menu.id = role_menu.menuId " +
                    "INNER JOIN twp_role role ON role.id = role_menu.roleId " +
                    "INNER JOIN twp_role_user role_user ON role.id = role_user.roleId " +
                    "INNER JOIN twp_manage_user u on u.id = role_user.manageUserId " +
                    "WHERE u.id = :urid"
    )
    List<Menu> findAllByUid(@Param("urid") Integer urid);
}